package com.ayi.dao.bookdao;

import com.ayi.bean.Book;
import com.ayi.utils.GetConn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Ayingzz
 * @create 2021/12/1 22:38
 */
public class UpdateBook {

    /**
     * 加入购物车时，更新其库存-1
     * @param id
     * @param i
     * @return
     */
    public boolean updateInventory(int id, int i) {
        Connection conn = new GetConn().getConnection();
        Book book = new QueryBook().queryBookById(id);
        String sql = "update Books set inventory = ? where id = ?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, book.getInventory() + i);
            ps.setInt(2, id);
            ps.execute();
            return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    /**
     * 在图书表里修改一条记录
     * @param book
     * @return
     */
    public boolean updateBookFromBooksById(Book book) {
        Connection conn = new GetConn().getConnection();
        StringBuilder sb = new StringBuilder("update books set");
        sb.append(" name = ?,");
        sb.append("type = ?,");
        sb.append("author = ?,");
        sb.append("inventory = ?,");
        sb.append("price = ?,");
        sb.append("details = ?");
        sb.append(" where id = ?");
        String sql = sb.toString();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, book.getName());
            ps.setString(2, book.getType());
            ps.setString(3, book.getAuthor());
            ps.setInt(4, book.getInventory());
            ps.setDouble(5, book.getPrice());
            ps.setString(6, book.getDetails());
            ps.setInt(7, book.getId());
            ps.execute();
            return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }
}
